﻿using BusinessLayer.VDataEntities;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Http;
using TrialManagementTool.App_Start;
using TrialManagementTool.Helper;
using TrialManagementTool.Models;

namespace TrialManagementTool.Controllers.API
{
    [WebApiExceptionFilter]
    [APIAuthorize]
    public class CropController : ApiController
    {
        /// <summary>
        /// 获取除其他之外的作物列表
        /// </summary>
        /// <returns></returns>
        public VCrop[] GetAllCrops()
        {
            VCrop[] crops = BusinessLayer.CropBusiness.GetAllCropListWithoutOthers();
            return crops;
        }

        /// <summary>
        /// 作物选取
        /// </summary>
        /// <returns></returns>
        public string GetAllActiveCrops()
        {
            VCrop[] crops = BusinessLayer.CropBusiness.GetActiveCropList();
            List<BaseModel> result = new List<BaseModel>();
            BaseModel model = new BaseModel();

            foreach (VCrop v in crops)
            {
                model = new BaseModel();
                model.id = v.ID.ToString();
                model.value = v.Name;
                result.Add(model);
            }
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(result.GetType());
            string json = "";

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, result);
                json = Encoding.UTF8.GetString(ms.ToArray());
            }

            return json;
        }

        public void UpdateCropStatus(VCrop crop)
        {
            BusinessLayer.CropBusiness.ChangeStatus(crop.ID);
        }

        public void AddCrop(VCrop crop)
        {
            BusinessLayer.CropBusiness.AddCrop(crop.Name);
        }

        public VCrop[] GetAllActiveListCrops()
        {
            return BusinessLayer.CropBusiness.GetActiveCropList();
        }
    }
}
